package blockchain

import (
	"context"
	"private-domain-overseas-service/app/business/api/internal/svc"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type BlockchainWalletDao struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewBlockchainWalletDao(ctx context.Context, svcCtx *svc.ServiceContext) *BlockchainWalletDao {
	return &BlockchainWalletDao{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// BlockchainWalletConditionsOnly -  根据条件查询单个区块链钱包
func (l *BlockchainWalletDao) BlockchainWalletConditionsOnly(conditions []predicate.HzBlockchainWallet) (*ent.HzBlockchainWallet, error) {
	wallet, err := l.svcCtx.Orm.HzBlockchainWallet.
		Query().
		Where(conditions...).
		Only(l.ctx)
	if err != nil {
		return nil, err
	}
	return wallet, nil
}

// CreateBlockchainWallet 创建区块链钱包
func (l *BlockchainWalletDao) CreateBlockchainWallet(tx *ent.Tx, wallet *ent.HzBlockchainWallet) (*ent.HzBlockchainWallet, error) {
	clientDao := l.svcCtx.Orm.HzBlockchainWallet
	if tx != nil {
		clientDao = tx.HzBlockchainWallet
	}
	result, err := clientDao.Create().
		SetUserID(wallet.UserID).
		SetWalletAddress(wallet.WalletAddress).
		SetWalletPrivateKey(wallet.WalletPrivateKey).
		SetWalletStatus(wallet.WalletStatus).
		SetCreatedAt(time.Now().Unix()).
		SetUpdateAt(time.Now().Unix()).
		Save(l.ctx)
	if err != nil {
		return nil, err
	}
	return result, nil
}

// UpdateBlockchainWallet 更新区块链钱包
func (l *BlockchainWalletDao) UpdateBlockchainWallet(tx *ent.Tx, wallet *ent.HzBlockchainWallet) error {
	clientDao := l.svcCtx.Orm.HzBlockchainWallet
	if tx != nil {
		clientDao = tx.HzBlockchainWallet
	}
	_, err := clientDao.UpdateOneID(wallet.ID).
		SetWalletStatus(wallet.WalletStatus).
		SetUpdateAt(time.Now().Unix()).
		Save(l.ctx)
	if err != nil {
		return err
	}

	return nil
}
